import os
from PIL import Image
import threading
import time
from queue import Queue
import psutil  # 需要安装: pip install psutil


class ImageProcessor:
    """图片处理工具类 - 使用线程池处理图片"""

    def __init__(self, max_workers=2, max_memory_percent=70):
        self.task_queue = Queue()
        self.result_queue = Queue()
        self.max_workers = max_workers
        self.max_memory_percent = max_memory_percent
        self.workers = []
        self.running = False

    def start_workers(self):
        """启动工作线程"""
        self.running = True
        for i in range(self.max_workers):
            worker = threading.Thread(target=self._worker_loop)
            worker.daemon = True
            worker.start()
            self.workers.append(worker)

    def stop_workers(self):
        """停止工作线程"""
        self.running = False
        for worker in self.workers:
            worker.join(timeout=1.0)
        self.workers = []

    def _worker_loop(self):
        """工作线程循环"""
        while self.running:
            try:
                # 检查内存使用情况
                if psutil.virtual_memory().percent > self.max_memory_percent:
                    time.sleep(0.1)
                    continue

                # 获取任务
                task = self.task_queue.get(timeout=0.1)
                if task is None:
                    break

                # 处理任务
                result = self._process_image(*task)
                self.result_queue.put(result)
                self.task_queue.task_done()

            except Exception as e:
                # 异常处理
                self.result_queue.put(("error", str(e), task[0] if task else None))

    def _process_image(self, input_path, output_path, max_width=2000, quality=90):
        """处理单张图片"""
        try:
            # 打开图片
            img = Image.open(input_path)

            # 如果图片宽度超过限制，按比例缩小
            if img.width > max_width:
                ratio = max_width / img.width
                new_height = int(img.height * ratio)
                img = img.resize((max_width, new_height), Image.LANCZOS)

            # 确定最佳格式
            if img.mode in ("RGBA", "LA") or (
                img.mode == "P" and "transparency" in img.info
            ):
                format = "PNG"
            else:
                format = "JPEG"

            # 保存图片
            img.save(output_path, format=format, quality=quality)

            # 生成缩略图
            thumbnail = self._generate_thumbnail(img, (60, 60))

            return ("success", output_path, thumbnail)

        except Exception as e:
            return ("error", str(e), input_path)

    def _generate_thumbnail(self, img, size):
        """生成缩略图"""
        # 使用更小的尺寸生成缩略图
        img.thumbnail(size, Image.LANCZOS)
        return img

    def add_task(self, input_path, output_path, max_width=2000, quality=90):
        """添加处理任务"""
        self.task_queue.put((input_path, output_path, max_width, quality))

    def get_result(self, timeout=0.1):
        """获取处理结果"""
        try:
            return self.result_queue.get(timeout=timeout)
        except:
            return None

    def compress_image(self, input_path, output_path, max_width=2000, quality=90):
        """
        压缩图片并保存到指定路径

        :param input_path: 输入图片路径
        :param output_path: 输出图片路径
        :param max_width: 最大宽度限制
        :param quality: 保存质量 (1-100)
        :return: 压缩后的图片对象
        """
        return self._process_image(input_path, output_path, max_width, quality)


# 全局图片处理器实例
image_processor = ImageProcessor(max_workers=2, max_memory_percent=70)
image_processor.start_workers()
